import { MinusCircleOutlined } from '@ant-design/icons-vue'
import {
  Button,
  DatePicker,
  Form,
  FormItem,
  Input,
  InputNumber,
  message,
  Modal,
  Space,
  Textarea,
  TypographyText
} from 'ant-design-vue'
import { fa } from 'element-plus/lib/locale'
import moment from 'moment'
import { defineComponent, nextTick, onMounted, ref } from 'vue'
import { omit } from 'xe-utils'

import { marketingApi, redPacketRainApi } from '@/apis'
import { ExpressTempleteItem } from '@/apis/jindouGiftTypes'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import UploadFile from '@/components/UploadFile'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { useDialog } from '@/hooks'
import { download, downloadWithoutName } from '@/utils'

export default defineComponent({
  name: 'RedPacketRainConfig',
  setup() {
    const showDialog = ref(false)
    const showDialogResult = ref(false)
    const dialogLoading = ref(false)

    const optionItemCur = ref({} as ExpressTempleteItem)
    const resultData = ref({})
    const resultItemId = ref()
    const { showConfirm } = useDialog()

    const tableRef = ref({} as ProTableRef)
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        toolbarConfig: {
          slots: {
            buttons: 'batchButtons'
          }
        },
        // formConfig: {
        //   items: [
        //     {
        //       title: '活动标题',
        //       field: 'name',
        //       itemRender: {
        //         name: TABLE_ITEM_RENDER.AInput,
        //         props: {
        //           placeholder: '请输入',
        //           allowClear: true
        //         }
        //       }
        //     },
        //     {
        //       itemRender: {
        //         name: TABLE_RENDERER.FormItemBtns
        //       }
        //     }
        //   ]
        // },
        columnConfig: {
          minWidth: 100
        },

        columns: [
          {
            title: '场次',
            field: 'id'
          },
          {
            title: '标题',
            field: 'title'
          },
          {
            title: '活动时间',
            field: 'activityTime',
            minWidth: 150,
            formatter: [TABLE_FORMAT.Date, 'yyyy-MM-dd HH:mm:ss']
          },
          {
            title: '持续时间',
            field: 'period',
            slots: {
              default: 'period'
            }
          },
          {
            title: '创建时间',
            field: 'createTime',
            minWidth: 150,
            formatter: [TABLE_FORMAT.Date, 'yyyy-MM-dd HH:mm:ss']
          },
          {
            title: '状态',
            slots: {
              default: 'status'
            },
            width: 100
          },
          {
            title: '是否发布',
            slots: {
              default: 'isPublish'
            },
            width: 100
          },
          {
            title: '操作员',
            field: 'operator'
          },
          {
            title: '操作',
            fixed: 'right',
            slots: {
              default: 'operation'
            },
            width: 400
          }
        ],
        pagerConfig: {
          pageSize: 15
        },
        proxyConfig: {
          seq: true,
          form: true,
          props: {
            result: 'dataList',
            total: 'page.totalCount'
          },
          ajax: {
            query: async ({ page, form }) => {
              const data = await redPacketRainApi.getRedPacketRainList({
                pageParameter: {
                  pageSize: page.pageSize,
                  currentPage: page.currentPage
                },
                ...form
              })
              return data
            }
          }
        }
      }
    } as ProTableProps)

    const tableRefResult = ref({} as ProTableRef)
    const tableConfigResult = ref({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        toolbarConfig: {
          slots: {
            buttons: 'batchButtons'
          }
        },
        columnConfig: {
          minWidth: 100
        },

        columns: [
          {
            title: '昵称',
            field: 'nickname'
          },
          {
            title: '手机',
            field: 'phone'
          },
          {
            title: '积分',
            field: 'point'
          }
        ],
        pagerConfig: {
          pageSize: 15
        },
        proxyConfig: {
          seq: true,
          form: true,
          props: {
            result: 'records.dataList',
            total: 'records.page.totalCount'
          },
          ajax: {
            query: async ({ page, form }) => {
              const data = await redPacketRainApi.getRedPacketRainResultData({
                id: resultItemId.value,
                pageParameter: {
                  pageSize: page.pageSize,
                  currentPage: page.currentPage
                },
                ...form
              })
              return data
            }
          }
        }
      }
    } as ProTableProps)

    //启用禁用操作
    function handleForbidden(item) {
      showConfirm({
        content:
          item.status == 1 ? '确认禁用该运费模板？' : '确认启用运费模板？',
        onOk: async () => {
          try {
            await marketingApi.upDownExpressTemplete(item.id)
            tableRef.value.refresh()
          } catch (error) {}
        }
      })
    }

    function handlePublish(item) {
      showConfirm({
        content: item.isPublish == 0 ? '确认发布活动？' : '确认取消发布活动？',
        onOk: async () => {
          try {
            await redPacketRainApi.publishRedPacketRain(item.id)
            message.success('操作成功')
            tableRef.value.refresh()
          } catch (error) {}
        }
      })
    }

    function handleDelete(item) {
      showConfirm({
        content: '确认删除活动？',
        onOk: async () => {
          try {
            await redPacketRainApi.deleteRedPacketRain(item.id)
            message.success('操作成功')
            tableRef.value.refresh()
          } catch (error) {}
        }
      })
    }

    function handleOver(item) {
      showConfirm({
        content: '确认结束活动？',
        onOk: async () => {
          try {
            await redPacketRainApi.overRedPacketRain(item.id)
            message.success('操作成功')
            tableRef.value.refresh()
          } catch (error) {}
        }
      })
    }

    function showResultModal(item) {
      resultItemId.value = item.id
      redPacketRainApi
        .getRedPacketRainResultData({
          id: item.id,
          pageParameter: {
            pageSize: 1,
            currentPage: 1
          }
        })
        .then(res => {
          resultData.value = res
          showDialogResult.value = true
        })
    }

    //新增梯度
    function addTd() {
      optionItemCur.value.gradient.push({})
    }

    //新增
    function add() {
      optionItemCur.value = { gradient: [{}, {}, {}] } as ExpressTempleteItem
      showDialog.value = true
    }

    //编辑
    function edit(item) {
      redPacketRainApi.getRedPacketRainInfo(item.id).then(res => {
        optionItemCur.value = {
          ...res,
          activityTime: moment(res.activityTime)
        }
        showDialog.value = true
      })
    }

    //编辑/新增确定
    async function dialogConfirm() {
      if (!optionItemCur.value.title) {
        message.error('请输入活动标题')
        return
      }
      if (!optionItemCur.value.subTitle) {
        message.error('请输入活动副标题')
        return
      }
      if (!optionItemCur.value.activityTime) {
        message.error('请输入活动时间')
        return
      }

      if (!optionItemCur.value.backImg) {
        message.error('请上传活动背景图')
        return
      }
      if (!optionItemCur.value.showImg) {
        message.error('请上传红包样式图')
        return
      }
      if (!optionItemCur.value.period) {
        message.error('请输入持续时间')
        return
      }
      if (!optionItemCur.value.limitPerson) {
        message.error('请输入最大参与限制')
        return
      }
      if (!optionItemCur.value.period) {
        message.error('请输入持续时间')
        return
      }
      const gradients = optionItemCur.value.gradient
      console.log(gradients, '===gradients')
      let beforeGoalPerson = null
      for (const gradient of gradients) {
        if (
          gradient.goalPerson === undefined ||
          gradient.releasePoint === undefined ||
          gradient.maxPoint === undefined ||
          gradient.minPoint === undefined ||
          gradient.singlePoint === undefined
        ) {
          message.error('请输入完整梯度数据')
          return
        }
        if (Number(gradient.maxPoint) < Number(gradient.minPoint)) {
          message.error('最大积分不可小于最小积分')
          return
        }
        if (
          beforeGoalPerson &&
          Number(gradient.goalPerson) <= Number(beforeGoalPerson)
        ) {
          message.error('请按照从小到大的梯度顺序填写')
          return
        }
        beforeGoalPerson = gradient.goalPerson
      }

      try {
        dialogLoading.value = true
        const params = {
          ...optionItemCur.value,
          activityTime: new Date(optionItemCur.value.activityTime).valueOf()
        }
        if (optionItemCur.value.id) {
          await redPacketRainApi.updateRedPacketRain(params)
        } else {
          await redPacketRainApi.createRedPacketRain(params)
        }
        showDialog.value = false
        message.success('操作成功')
        tableRef.value.refresh()
      } finally {
        dialogLoading.value = false
      }
    }

    function exportData() {
      redPacketRainApi
        .exportRedPacketRainResultData(resultItemId.value)
        .then(res => {
          download(res, '红包雨活动数据')
        })
    }

    return {
      tableRef,
      tableConfig,
      tableRefResult,
      tableConfigResult,
      showDialog,
      showDialogResult,
      resultData,
      dialogLoading,
      optionItemCur,
      exportData,
      dialogConfirm,

      handleForbidden,
      handlePublish,
      handleDelete,
      handleOver,
      showResultModal,
      addTd,
      add,
      edit
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            batchButtons: () => (
              <Space>
                <Button type="primary" onClick={() => this.add()}>
                  新增红包雨活动
                </Button>
              </Space>
            ),
            period: ({ row }) => {
              return row.period + '秒'
            },
            status: ({ row }) => {
              return (
                <Space>
                  {row.status == 0 ? (
                    <TypographyText type="danger">未开始</TypographyText>
                  ) : row.status == 1 ? (
                    <TypographyText type="success">进行中</TypographyText>
                  ) : (
                    <TypographyText type="danger">已结束</TypographyText>
                  )}
                </Space>
              )
            },
            isPublish: ({ row }) => {
              return (
                <Space>
                  {row.isPublish == 0 ? (
                    <TypographyText type="danger">未发布</TypographyText>
                  ) : (
                    <TypographyText type="success">已发布</TypographyText>
                  )}
                </Space>
              )
            },

            operation: ({ row }) => (
              <Space>
                {row.status === 0 && (
                  <Button
                    type="link"
                    size="small"
                    onClick={() => this.edit(row)}
                  >
                    编辑
                  </Button>
                )}
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handlePublish(row)}
                >
                  {row.isPublish === 0 ? '发布' : '取消发布'}
                </Button>
                {row.status === 1 && (
                  <Button
                    type="link"
                    size="small"
                    onClick={() => this.handleOver(row)}
                  >
                    结束
                  </Button>
                )}
                {row.status === 0 && row.isPublish === 0 && (
                  <Button
                    type="link"
                    size="small"
                    onClick={() => this.handleDelete(row)}
                  >
                    删除
                  </Button>
                )}
                {(row.status === 1 || row.status === 2) && (
                  <Button
                    type="link"
                    size="small"
                    onClick={() => this.showResultModal(row)}
                  >
                    查看数据
                  </Button>
                )}
              </Space>
            )
          }}
          {...this.tableConfig}
        />
        <Modal
          v-model:visible={this.showDialog}
          confirmLoading={this.dialogLoading}
          title={'编辑'}
          width={1200}
          destroyOnClose
          onOk={this.dialogConfirm}
        >
          <Form labelCol={{ span: 4 }}>
            <FormItem label={'活动标题'} required>
              <Input
                maxlength={60}
                v-model:value={this.optionItemCur.title}
                placeholder="请输入"
                style={{ width: '200px' }}
              />
            </FormItem>
            <FormItem label={'活动副标题'} required>
              <Input
                maxlength={60}
                v-model:value={this.optionItemCur.subTitle}
                placeholder="请输入"
                style={{ width: '200px' }}
              />
            </FormItem>
            <FormItem label={'活动时间'} required>
              <DatePicker
                v-model:value={this.optionItemCur.activityTime}
                placeholder="活动时间"
                showTime
              />
            </FormItem>
            <FormItem label={'活动背景图'} required>
              <UploadFile v-model={[this.optionItemCur.backImg, 'urls']}>
                上传图片
              </UploadFile>
              <div style={{ color: '#666666' }}>建议尺寸750*1624</div>
            </FormItem>
            <FormItem label={'红包样式图'} required>
              <UploadFile v-model={[this.optionItemCur.showImg, 'urls']}>
                上传图片
              </UploadFile>
              <div style={{ color: '#666666' }}>建议尺寸160*260</div>
            </FormItem>

            <FormItem label={'持续时间'} required>
              <InputNumber
                v-model:value={this.optionItemCur.period}
                placeholder="请输入"
                min={0}
                maxlength={60}
                precision={0}
                style={{ width: '100px' }}
              />
              {` 秒`}
            </FormItem>
            <FormItem label={'最大参与限制'} required>
              <InputNumber
                v-model:value={this.optionItemCur.limitPerson}
                placeholder="请输入"
                min={0}
                maxlength={9999999}
                precision={0}
                style={{ width: '100px' }}
              />
              {` 人`}
            </FormItem>
            <FormItem label={'梯度'}>
              {this.optionItemCur.gradient.map((k, index) => (
                <div style={{ marginBottom: '15px' }}>
                  {`满 `}
                  <InputNumber
                    min={0}
                    maxlength={9999999}
                    precision={0}
                    v-model:value={k.goalPerson}
                    placeholder="请输入"
                    style={{ width: '80px' }}
                  />
                  {` 人，投放 `}
                  <InputNumber
                    min={0}
                    maxlength={9999999}
                    precision={0}
                    v-model:value={k.releasePoint}
                    placeholder="请输入"
                    style={{ width: '80px' }}
                  />
                  {` 积分，最大积分 `}
                  <InputNumber
                    min={0}
                    maxlength={9999999}
                    precision={0}
                    v-model:value={k.maxPoint}
                    placeholder="请输入"
                    style={{ width: '80px' }}
                  />
                  {` ，最小积分 `}
                  <InputNumber
                    min={0}
                    maxlength={9999999}
                    precision={0}
                    v-model:value={k.minPoint}
                    placeholder="请输入"
                    style={{ width: '80px' }}
                  />
                  {` 单人中奖不超过 `}
                  <InputNumber
                    min={0}
                    maxlength={9999999}
                    precision={0}
                    v-model:value={k.singlePoint}
                    placeholder="请输入"
                    style={{ width: '80px' }}
                  />
                  {` 积分`}
                  <MinusCircleOutlined
                    style={{ marginLeft: '10px' }}
                    onClick={() => this.optionItemCur.gradient.splice(index, 1)}
                  />
                </div>
              ))}
              <Button onClick={this.addTd} style={{ marginTop: '20px' }}>
                增加梯度
              </Button>
            </FormItem>
            <FormItem label={'活动说明'}>
              <Textarea
                placeholder="请输入"
                maxlength={999}
                v-model:value={this.optionItemCur.description}
              />
            </FormItem>
          </Form>
        </Modal>

        <Modal
          v-model:visible={this.showDialogResult}
          title={'中奖明细'}
          width={800}
          destroyOnClose
        >
          <div style={{ display: 'flex' }}>
            <div>参与人数：{this.resultData.joinNum} 人 </div>
            <div style={{ marginLeft: '30px' }}>
              中奖：{this.resultData.prizeNum} 人{' '}
            </div>
            <div style={{ marginLeft: '30px' }}>
              发放积分：{this.resultData.releasePoint} 分{' '}
            </div>
          </div>
          <ProTable
            ref="tableRefResult"
            v-slots={{
              batchButtons: () => (
                <Space>
                  <Button type="primary" onClick={() => this.exportData()}>
                    导出
                  </Button>
                </Space>
              )
            }}
            {...this.tableConfigResult}
          />
        </Modal>
      </div>
    )
  }
})
